import React, { useEffect } from 'react';
import { NavigationContainer, DefaultTheme } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { APP_STATE } from '@/constants';
//import {watchGeoLocation} from '@/services/geolocation';
import useDeviceAndNetInfo from '@/services/useDeviceAndNetInfo';
import LoginStore from '@/stores/loginStore';
import colors from '@/Themes/Colors';
// Screens Objects
import LaunchScreen from '../screens/Launch';
import LoginStack from './loginStack';
import HomeStack from './homeStack';
import { Modal } from '@ant-design/react-native';

const Stack = createStackNavigator();

const appTheme = {
  ...DefaultTheme,
  colors: {
    ...DefaultTheme.colors,
    primary: colors.primary,
    background: colors.grey50,
    card: 'rgb(255, 255, 255)',
    text: colors.panegrey,
    border: 'rgb(199, 199, 204)',
    notification: 'rgb(255, 69, 58)',
  },
};

export default function RootNavigation() {
  const loginStore = LoginStore.useStore();
  const deviceNetInfo = useDeviceAndNetInfo();

  useEffect(() => {
    if (loginStore.authState === APP_STATE.UNKNOWN) {
      loginStore.checkLogin();
    }
    deviceNetInfo.ifChange && deviceNetInfo.net_type !== null
      ? Modal.alert('网络状态发生改变，请退出重新登录')
      : '';
    //const unwatch = watchGeoLocation();
    return () => {
      //unwatch();
    };
  }, [loginStore]);
  useEffect(() => {
    if (
      deviceNetInfo.isConnected &&
      (loginStore.mrsauthState.action === 'unknown' ||
        loginStore.mrsauthState.action === 'retry')
    ) {
      // 网络连接上时auth state是unknown 或retry时重新检测登录状态
      loginStore.checkLogin();
    }
  }, [deviceNetInfo.isConnected, loginStore.mrsauthState.action]);
  useEffect(() => {
    const refreshIntervalMs = 60 * 1000; // rn android setTimeout定时过长时会有warning
    let refreshTimer;
    console.log(refreshTimer, loginStore.tokenRefreshTime);
    let timeoutTs = loginStore.tokenRefreshTime.expire_time - Date.now();
    if (timeoutTs > 0) {
      refreshTimer = setInterval(async () => {
        timeoutTs -= refreshIntervalMs;
        if (timeoutTs < refreshIntervalMs) {
          await loginStore.refreshToken();
          if (refreshTimer) {
            clearInterval(refreshTimer);
            refreshTimer = null;
          }
          //console.log('settimeout refreshtoken', timeoutTs);
        }
      }, refreshIntervalMs);
    }
    return () => {
      if (refreshTimer) {
        clearInterval(refreshTimer);
        refreshTimer = null;
      }
    };
  }, [loginStore, loginStore.tokenRefreshTime.expire_time]);
  return (
    <NavigationContainer theme={appTheme}>
      <Stack.Navigator headerMode="none">
        {loginStore.authState === APP_STATE.PRIVATE ? (
          <Stack.Screen name={HomeStack.routeName} component={HomeStack} />
        ) : loginStore.authState === APP_STATE.PUBLIC ? (
          <Stack.Screen name={LoginStack.routeName} component={LoginStack} />
        ) : (
          <Stack.Screen
            name={LaunchScreen.routeName}
            component={LaunchScreen}
          />
        )}
      </Stack.Navigator>
    </NavigationContainer>
  );
}
